const { pool } = require('../config/mysqlConfig');

// 为群组表添加状态字段的迁移脚本
async function addGroupStatusFields() {
  const connection = await pool.getConnection();
  
  try {
    console.log('开始为群组表添加状态字段...');
    
    // 检查字段是否已存在
    const [columns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'groups' 
      AND COLUMN_NAME IN ('status', 'disbanded_at', 'disbanded_by')
    `);
    
    const existingColumns = columns.map(col => col.COLUMN_NAME);
    
    // 添加 status 字段
    if (!existingColumns.includes('status')) {
      await connection.query(`
        ALTER TABLE \`groups\` 
        ADD COLUMN status ENUM('active', 'disbanded') NOT NULL DEFAULT 'active'
      `);
      console.log('✓ 添加 status 字段成功');
    } else {
      console.log('✓ status 字段已存在');
    }
    
    // 添加 disbanded_at 字段
    if (!existingColumns.includes('disbanded_at')) {
      await connection.query(`
        ALTER TABLE \`groups\` 
        ADD COLUMN disbanded_at TIMESTAMP NULL
      `);
      console.log('✓ 添加 disbanded_at 字段成功');
    } else {
      console.log('✓ disbanded_at 字段已存在');
    }
    
    // 添加 disbanded_by 字段
    if (!existingColumns.includes('disbanded_by')) {
      await connection.query(`
        ALTER TABLE \`groups\` 
        ADD COLUMN disbanded_by VARCHAR(255) NULL
      `);
      console.log('✓ 添加 disbanded_by 字段成功');
    } else {
      console.log('✓ disbanded_by 字段已存在');
    }
    
    // 添加索引
    try {
      await connection.query(`
        ALTER TABLE \`groups\` 
        ADD INDEX idx_status (status)
      `);
      console.log('✓ 添加 status 索引成功');
    } catch (error) {
      if (error.code === 'ER_DUP_KEYNAME') {
        console.log('✓ status 索引已存在');
      } else {
        throw error;
      }
    }
    
    console.log('群组表状态字段迁移完成！');
    
  } catch (error) {
    console.error('迁移失败:', error);
    throw error;
  } finally {
    connection.release();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  addGroupStatusFields()
    .then(() => {
      console.log('迁移成功完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('迁移失败:', error);
      process.exit(1);
    });
}

module.exports = { addGroupStatusFields };
